package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.hmdp.dto.UserDTO;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class RedisConvertUtil {

    public static Map<String,Object> beanToMap(Object o){
//        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(o, new HashMap<>(),
//                CopyOptions.create()
//                        .setIgnoreNullValue(true)
//                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
//            return stringObjectMap;
        Map<String, Object> stringObjectMap = new HashMap<>();
        UserDTO user = (UserDTO) o;
        stringObjectMap.put("id",user.getId().toString());
        stringObjectMap.put("nickName",user.getNickName());
        stringObjectMap.put("icon",user.getIcon());
        return stringObjectMap;
    }
    public static UserDTO MapToBean(Map<Object,Object> map) throws NoSuchFieldException, IllegalAccessException {
//        public class UserDTO {
//            private Long id;
//            private String nickName;
//            private String icon;
        UserDTO user = new UserDTO();
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            if (key == null || value == null || value.equals("") ) continue;
            String fieldName = key.toString(); // 确保键转为字符串
            Field field = user.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(user,value.toString());
        }
        return user;
    }
}
